const setWs = (callback) => {
  const ws = new WebSocket(`ws://${location.host}/api/machine/status`);
  ws.onopen = (event) => {
    // 建立链接成功后可以进行一些处理
    console.log('onopen = ', event);

    // 主动给服务器发送消息
    ws.send('from client', () => {
      console.log('success');
    })
  }
  ws.onclose = (event) => {
    // 链接关闭 - 进行一些处理
    console.log('onclose = ', event);
  }
  ws.onerror = (event) => {
    // ws链接异常处理
    console.log('onerror = ', event);
  }
  ws.onmessage = (event) => {
    // 正常接受到消息进行处理
    console.log('onmessage = ', event);
    if(callback) {
      callback(event.data);
    }
  };
}

const getMachineData = () => {
  $.ajax({
    url: '/machine/info?id=1',
    dataType: 'json',
    success: (res) => {
      console.log('res', res);
      $('#name').text(res?.data?.name??'');
      $('#status').text(res?.data?.status??'');
    }
  })
}

// 初始获取machine数据
getMachineData();
// 建立ws链接
const ws = setWs(status => {
  $('#status').text(status);
});

// 启动操作
const onRun = () => {
  $.ajax({
    url: '/machine/run?id=1',
    dataType: 'json',
    success: (res) => {
      console.log('res', res);
      $('#status').text(res?.data??'');
    }
  })
}
// 停止操作
const onStop = () => {
  $.ajax({
    url: '/machine/stop?id=1',
    dataType: 'json',
    success: (res) => {
      console.log('res', res);
      $('#status').text(res?.data??'');
    }
  })
}